﻿using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Events;

//把这个脚本挂在中间场景(LoadingSceen)中
[XLua.LuaCallCSharp]
public class SceneLoader : MonoBehaviour
{
    public UnityEvent<float> loadSceneUdateEvent;
    public static AsyncOperation loadSceneAo;
    public static AsyncOperation unLoadSceneAo;
    private static string _nextSceneName;//要加载的下一个场景
    private static string LoadingScenePath = "Assets/DevFramework/SceneLoader/LoadingScene.unity";

    public static void LoadScene(string nextSceneName)
    {
        _nextSceneName = nextSceneName;
        /*#if UNITY_EDITOR
                if (AssetManager.instance.loadMode== LoadMode.editor)
                    UnityEditor.SceneManagement.EditorSceneManager.LoadScene(LoadingScenePath);
                else
        #endif*/
        if (AssetManager.instance.loadMode == LoadMode.runTime) AssetManager.LoadAsset<Object>(LoadingScenePath);
        SceneManager.LoadScene(LoadingScenePath, LoadSceneMode.Additive);
    }

    public static void UnLoadScene(string sceneName)
    {
        unLoadSceneAo = SceneManager.UnloadSceneAsync(sceneName);
    }

    public static void UnLoadScene(Scene scene)
    {
        unLoadSceneAo = SceneManager.UnloadSceneAsync(scene);
    }

    private void Start()
    {
        if (AssetManager.instance.loadMode == LoadMode.runTime)
        {
            AssetManager.instance.Load<Object>(_nextSceneName);
        }
        /*#if UNITY_EDITOR
                if (AssetManager.instance.loadMode == LoadMode.editor)
                 loadSceneAo=   UnityEditor.SceneManagement.EditorSceneManager.LoadSceneAsync(_nextSceneName);
                else
        #endif*/
        loadSceneAo = SceneManager.LoadSceneAsync(_nextSceneName, LoadSceneMode.Additive);
    }

    private void Update()
    {
        if (loadSceneAo != null)
        {
            //更新进度条
            loadSceneUdateEvent.Invoke(loadSceneAo.progress / 0.9f);
            if (loadSceneAo.isDone)
            {
                UnLoadScene(LoadingScenePath);//卸载中间场景
                SceneManager.SetActiveScene(SceneManager.GetSceneByPath(_nextSceneName));
            }
        }
    }
}